#include<stdio.h>
#include<string.h>
#include<stdlib.h>

#ifdef READCONFIG_DEBUG_ENABLE
#define READCONFIG_LOG_E(fmt, args...) fprintf(stderr, "[%s] [%d] "fmt, __FUNCTION__, __LINE__, ##args); 
#define READCONFIG_LOG_I(fmt, args...) fprintf(stderr, "[%s] [%d] "fmt, __FUNCTION__, __LINE__, ##args); 
#define READCONFIG_LOG_W(fmt, args...) fprintf(stderr, "[%s] [%d] "fmt, __FUNCTION__, __LINE__, ##args); 
#else
#define READCONFIG_LOG_E(fmt, args...) fprintf(stderr, "[%s] [%d] "fmt, __FUNCTION__, __LINE__, ##args); 
#define READCONFIG_LOG_I(fmt, args...)
#define READCONFIG_LOG_W(fmt, args...)
#endif


//configs obtained from file
struct configs{
	char ip[64];
	int port;	
};

static void set_option(const char *opt,const char *val, struct configs* conf)
{
	unsigned long long ival = 0;
	if(strcmp(opt,"port")==0)
	{
		ival = atoll(val);
		conf->port = ival;
	}else if(strcmp(opt,"ip")==0)
	{
		if (snprintf(conf->ip, sizeof(conf->ip), "%s", val) >= sizeof(conf->ip))
			READCONFIG_LOG_E("buffer over flow\n");
	}
	else{
		READCONFIG_LOG_E("unknow opt:%s", opt);
	}
	return;
}

static int initialize_config(const char *config_file, struct configs* confs)
{
	char			line[128], var[sizeof(line)], val[sizeof(line)];
	FILE 			*fp;
	if (config_file != NULL && (fp = fopen(config_file, "r")) != NULL) {
		READCONFIG_LOG_I("init_ctx: config file %s\n", config_file);

		while (fgets(line, sizeof(line), fp) != NULL) {

			/* Skip comments and empty lines */
			if (line[0] == '#' || line[0] == '\n')
				continue;

			/* Trim trailing newline character */
			int i = 0;
			for (i = strlen(line) - 1; i >= 0; --i) {
				if (line[i] == '\n' || line[i] == '\r')
						line[i] = '\0';
				}
				else 
					break;
				}
			}
			if (sscanf(line, "%s %[^#\n]", var, val) != 2)
				READCONFIG_LOG_E("init_ctx: bad line: [%s]\n",line);
			set_option(var, val, confs);
		}
		(void) fclose(fp);
	}
	else
		return -1;
	return 0;
	/* Third pass: process command line args */
}
//文件格式
//ip 10.200.27.69
//port 10000
int main(int argc, char** argv)
{
		struct configs confs;
		memset(&confs, 0, sizeof(struct configs));
		initialize_config(argv[1], &confs);	
		printf("ip:%s port:%d\n", confs.ip, confs.port);
		return 0;
}
